package com;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

import com.bean.LoginSuccessBean;
import com.interfaces.IEvent;
import com.interfaces.IEventListener;
import com.message.MsgId;
import com.util.LogUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.ListIterator;
import java.util.Map;

/**
 * Created by Mars on 2017/9/20.
 */

public class MainPresenter {

    private static MainPresenter mMp;
    private Intent mServiceIntent = null;
    private Messenger mRemoteMessenger;

    private LinkedHashMap<Object, IEventListener> mListEventListener = null;
    private Messenger mMessenger;
    private boolean mBinded;
    private boolean mbLogin;


    public static MainPresenter getInstance() {
        if (mMp == null) {
            mMp = new MainPresenter();
        }
        return mMp;
    }

    MainPresenter() {
        mListEventListener = new LinkedHashMap<>();
    }

    public void startService() {
        LogUtil.e("startService");
        if (mServiceIntent == null) {
            mServiceIntent = new Intent();
            MyApp context = MyApp.getInstance();
            mServiceIntent.setClass(context, LotteryService.class);
            // TODO: 2017/9/25 绑定服务
            mBinded = context.bindService(mServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
        }
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            LogUtil.e("onServiceConnected");
            mRemoteMessenger = new Messenger(service);
            mMessenger = new Messenger(mHandler);

            sendReplyMessage2Service();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mRemoteMessenger = null;
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            IEvent iEvent = null;

            switch (msg.what) {
                default:
                    iEvent = (IEvent) msg.obj;
                    break;
            }
            if (iEvent != null) {
                broadcastEvent(mListEventListener, iEvent);
            }
        }
    };

    private void broadcastEvent(HashMap<Object, IEventListener> hashMap, IEvent iEvent) {
        if (!hashMap.isEmpty()) {
            ListIterator<Map.Entry<Object, IEventListener>> iterator =
                    new ArrayList<>(hashMap.entrySet()).listIterator(hashMap.size());
            while (iterator.hasPrevious()) {
                // TODO: 2017/9/25 iEvent 处理

                if (iEvent instanceof LoginSuccessBean) {
                    LoginSuccessBean event = (LoginSuccessBean) iEvent;
                    if ("200".equals(event.getCode())) {
                        mbLogin = true;
                    } else {
                        mbLogin = false;
                    }
                }

                if (iterator.previous().getValue().onEvent(iEvent)) {
                    break;
                }

            }

        }
    }

    public void stopService(Context ctx) {
        ctx = ctx.getApplicationContext();

        try {
            if (mBinded) {
                ctx.unbindService(mServiceConnection);
                mBinded = false;
            }
        } catch (IllegalArgumentException e) //Service not registered if not binded
        {
            e.printStackTrace();
        }

        if (mServiceIntent != null) {
            ctx.stopService(mServiceIntent);
        }

        mBinded = false;
    }

    private void sendReplyMessage2Service() {
        LogUtil.e("sendReplyMessage2Service");
        if (mRemoteMessenger == null) {
            return;
        }

        int what = MsgId.MSG_CLIENT_CALLBACK_HANDLER;
        int arg1 = 0;
        int arg2 = 0;
        Object obj = null;

        Message msg = Message.obtain(null, what, arg1, arg2, obj);
        msg.replyTo = mMessenger;
        LogUtil.e("sendReplyMessage2Service" + msg.toString());

        try {
            mRemoteMessenger.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

        if (mRemoteMessenger == null) {
            return;
        }
    }

    public boolean sendRequestMessage2Service(short type, String body) {
        if (mRemoteMessenger == null) {
            LogUtil.e("mRemoteMessenger = null");
            return false;
        }

        int what = MsgId.MSG_CLIENT_REQUEST;
        int arg1 = type;
        int arg2 = 0;

        Message msg = Message.obtain(null, what, arg1, arg2, body);

        LogUtil.e(msg.what + "");
        try {
            mRemoteMessenger.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public void registerEventListener(Object obj, IEventListener listener) {
        mListEventListener.put(obj, listener);
    }

    public void unregisterEventListener(Object obj) {
        mListEventListener.remove(obj);
    }

}
